package org.market.domain.strategy.service.raffle;

import lombok.extern.slf4j.Slf4j;
import org.market.domain.strategy.model.entity.StrategyAwardEntity;
import org.market.domain.strategy.model.valobj.RuleTreeVO;
import org.market.domain.strategy.model.valobj.StrategyAwadRuleModelVO;
import org.market.domain.strategy.model.valobj.StrategyAwardStockKeyVO;
import org.market.domain.strategy.repository.IStrategyRepository;
import org.market.domain.strategy.service.AbstractRaffleStrategy;
import org.market.domain.strategy.service.armory.IStrategyDispatch;
import org.market.domain.strategy.service.rule.chain.ILogicChain;
import org.market.domain.strategy.service.rule.chain.factory.DefaultChainFactory;
import org.market.domain.strategy.service.rule.tree.engine.IDecisionEngine;
import org.market.domain.strategy.service.rule.tree.factory.DefaultLogicFactory;
import org.market.domain.strategy.service.rule.tree.factory.DefaultRuleTreeFactory;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;

/**
 * @Author: Insight
 * @Description: TODO
 * @Date: 2025/2/10 下午11:33
 * @Version: 1.0
 */
@Slf4j
@Service
public class DefaultRaffleStrategy extends AbstractRaffleStrategy {

    @Resource
    private DefaultLogicFactory logicFactory;


    public DefaultRaffleStrategy(IStrategyRepository strategyRepository, IStrategyDispatch strategyDispatch, DefaultChainFactory chainFactory, DefaultRuleTreeFactory ruleTreeFactory) {
        super(strategyRepository, strategyDispatch, chainFactory, ruleTreeFactory);
    }

    @Override
    public DefaultChainFactory.StrategyAwardVO logicChain(String userId, Long strategyId) {
        ILogicChain logicChain = chainFactory.buildLogicChain(strategyId);
        return logicChain.logic(userId,strategyId);
    }

    @Override
    public DefaultRuleTreeFactory.StrategyAwardVO loginRuleTree(String userId, Long strategyId, Integer awardId) {
        StrategyAwadRuleModelVO strategyAwadRuleModelVO = strategyRepository.queryStrategyAwardRuleModel(strategyId,awardId);

        if(strategyAwadRuleModelVO == null) {
            return DefaultRuleTreeFactory.StrategyAwardVO.builder()
                    .awardId(awardId)
                    .build();
        }

        RuleTreeVO ruleTreeVO = strategyRepository.queryRuleTreeVOByTreeId(strategyAwadRuleModelVO.getRuleModels());
        if (ruleTreeVO == null) {
            throw new RuntimeException("规则树库表存在参数错误!!!!");
        }

        IDecisionEngine decisionEngine = ruleTreeFactory.buildRuleTree(ruleTreeVO);
        return decisionEngine.process(userId,strategyId,awardId);
    }

    @Override
    public StrategyAwardStockKeyVO takeQueueValue() throws InterruptedException {
        return strategyRepository.queryTakeQueueValue();
    }

    @Override
    public void updateStrategyAwardStock(Long strategyId, Integer awardId) {
        strategyRepository.updateStrategyAwardStock(strategyId,awardId);
    }
}
